package com.itheima.pxgl.aspect;

import com.itheima.pxgl.annotation.AutoFill;
import com.itheima.pxgl.common.constant.AutoFillConstant;
import com.itheima.pxgl.common.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class AutoFillAspect {
    /**
     * 切点表达式
     */
    @Pointcut("execution(* com.itheima.pxgl.mapper.*.*(..)) && @annotation(com.itheima.pxgl.annotation.AutoFill)")
    public void autoFillPointCut(){}
    /**
     * 要做的事情
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始填充字段···");
//        获取拦截的方法的数据库上的操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //方法签名对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);  //获得方法上的注解对象
        OperationType value = annotation.value(); //获得数据库类型
//        获取对象
        Object[] args = joinPoint.getArgs();
        if(args.length ==0 || args == null){
            return;
        }
        Object arg = args[0];
        LocalDateTime nowTime = LocalDateTime.now();
//        如果为插入类型，则将时间等插入进去
        if(value == OperationType.INSERT){
            log.info("开始Insert方法");
            log.info("开始{}",arg);
            try {
                Method createTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                createTime.invoke(arg,nowTime);
                log.info("开始{}",arg);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
